package cn.fy.appcode.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import cn.fy.appcode.R;

import cn.fy.appcode.MainActivity;

public class BindService extends Service  {
    //声明IBinder接口的一个接口变量mBinder
    public final IBinder mBinder = new LocalBinder();
    private NotificationManager mNM;
    private int NOTIFICATION = 2;
    //LocalBinder是继承Binder的一个内部类
    public class LocalBinder extends Binder {
        public BindService getService() {
            return BindService.this;
        }
    }
    @Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Log.e(getClass().getName(), "onCreate");
        showNotification();
    }

    @Override
    public void onDestroy() {
        Log.e(getClass().getName(), "onDestroy");
        mNM.cancel(NOTIFICATION);
        Toast.makeText(this, "销毁", Toast.LENGTH_SHORT).show();
    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(getClass().getName(), "onBind");
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(getClass().getName(), "onUnbind");
        return super.onUnbind(intent);
    }

    private void showNotification() {
        CharSequence text = "开始";
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
        Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker(text)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("绑定服务")
                .setContentText(text)
                .setContentIntent(contentIntent)
                .build();
        mNM.notify(NOTIFICATION, notification);
        Log.e(getClass().getName(), "通知栏已出");
    }
}
